﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Reflection;
using System.Collections;
using System.Data;

namespace FOBVT.Web.DBUtility
{
	/// <summary>
	/// 所有数据表对象的基类
	/// </summary>
	[Serializable]
	public class BaseInfo
	{
		private PropertyInfo[] _propertyInfos = null;

		public virtual bool Add()
		{
			return DataAccess.Insert(this);
		}

		public virtual bool Delete()
		{
			return DataAccess.Delete(this);
		}

		public virtual bool Exist()
		{
			return DataAccess.Exist(this);
		}

		public virtual bool Save()
		{
			if (this.Exist())
			{
				return this.Update();
			}
			return this.Add();
		}

		public virtual bool Update()
		{
			return DataAccess.Update(this);
		}

		public virtual bool Select()
		{
			return DataAccess.SelectInfo(this);
		}

		public virtual bool Select(string WhereClause)
		{
			return DataAccess.SelectInfo(this, WhereClause);
		}

		public virtual bool Select(string WhereClause, IDataParameter[] parameters)
		{
			return DataAccess.SelectInfo(this, WhereClause, parameters);
		}

		/// <summary>
		/// 将Hashtable转为类
		/// </summary>
		/// <param name="data"></param>
		/// <returns></returns>
		public bool SetInternalData(Hashtable data)
		{
			foreach (PropertyInfo pi in this.PropertyInfos)
			{
				try
				{
					if (Attribute.GetCustomAttribute(pi, typeof(PropertyAttribute), false) is PropertyAttribute)
					{
						pi.SetValue(this, Read(data[pi.Name]), null);
					}
				}
				catch (Exception ex)
				{
					throw ex;
				}
			}
			return true;
		}

		/// <summary>
		/// 将数据库值转化为程序值
		/// </summary>
		/// <param name="DBValue"></param>
		/// <returns></returns>
		protected object Read(object DBValue)
		{
			if (DBValue == this.DBNULL)
			{
				return this.CSNULL;
			}
			return DBValue;
		}

		/// <summary>
		/// 数据库空值
		/// </summary>
		protected virtual object DBNULL
		{
			get
			{
				return DBNull.Value;
			}
		}

		/// <summary>
		/// 程序空值null
		/// </summary>
		protected virtual object CSNULL
		{
			get
			{
				return null;
			}
		}

		private Type InfoType
		{
			get
			{
				return base.GetType();
			}
		}

		private PropertyInfo[] PropertyInfos
		{
			get
			{
				if (this._propertyInfos == null)
				{
					this._propertyInfos = this.InfoType.GetProperties();
				}
				return this._propertyInfos;
			}
		}
	}
}